<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\Roles;
use App\Models\RollMaster;
use App\Models\RollRestlen;
use App\Models\RollReturn;
use App\Models\RollTransfer;
use App\Models\UserStoreLogs;
use App\Models\Warranty;
use App\Services\StoreService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{

    /*
     * 安装数量，按地区划分*/
    protected function chartA1(Request $request)
    {
        $user_id = session()->get('admin.id');
        $user_type = session()->get('admin.user_type');
        $year = $request->input('year');
        $year = $year ?: date('Y');
        $r = DB::table('region_master')->orderBy('id')->get('id');
        $region = Arr::pluck($r, 'id'); // 地区
        $tm = []; // 补零后的1-12
        foreach (range(1, 12) as $v) {
            $k = str_pad($v, 2, 0, STR_PAD_LEFT);
            $tm[$k] = 0;
        }
        $c1 = []; // 安装数量，按地区划分
        if ($user_type == 1) {
            $data = DB::select("SELECT date_format(installation_date,'%m') AS oaWonVEI,COUNT(id) AS tX1xYm5Q, region_id FROM warranty WHERE installation_date like '" . $year . "%' GROUP BY region_id,oaWonVEI");
        } elseif ($user_type == 2) {
            $data = DB::select("SELECT date_format(installation_date,'%m') AS oaWonVEI,COUNT(id) AS tX1xYm5Q, region_id FROM warranty WHERE installation_date like '" . $year . "%' and user_id in (select id from users where id='" . $user_id . "' or creator_id='" . $user_id . "') GROUP BY region_id,oaWonVEI");
        }
        foreach ($region as $k => $v) {
            $c1[$v] = $tm; // 地区
        }
        foreach ($data as $k => $v) {
            if (empty($c1[$v->region_id])) {
                $c1[$v->region_id] = [];
            }
            $c1[$v->region_id][$v->oaWonVEI] = $v->tX1xYm5Q;
        }
        $c1_1 = [
            'name' => ts('region_master.1'),
            'type' => 'line',
            'color' => '#1891ff',
            'data' => array_values($c1[1]),
        ];
        $c1_2 = [
            'name' => ts('region_master.2'),
            'type' => 'line',
            'color' => '#f9cc14',
            'data' => array_values($c1[2]),
        ];
        $c1_3 = [
            'name' => ts('region_master.3'),
            'type' => 'line',
            'color' => '#13c2c2',
            'data' => array_values($c1[3]),
        ];
        $c1_4 = [
            'name' => ts('region_master.4'),
            'type' => 'line',
            'color' => '#2fc25b',
            'data' => array_values($c1[4]),
        ];
        $c1_xAxis = $this->getMon1();
        $c1_legend = [ts('region_master.1'), ts('region_master.2'), ts('region_master.3'), ts('region_master.4')];
        return [
            'series' => [
                $c1_1,
                $c1_2,
                $c1_3,
                $c1_4,
            ],
            'title' => ts('AZSL'),
            'legend' => $c1_legend,
            'xAxis' => $c1_xAxis,
        ];
    }
    protected function chartA2(Request $request) {}

    protected function sd_index(Request $request)
    {
        $admin_id = session('admin.id');
        $user_id = session('admin.id');
        /*$jxs = DB::table('users')->where('status', 1)
            ->where('creator_id', $user_id)
            ->whereNull('deleted_at')
            ->where('user_type', 3)
            ->count();
        $kh = DB::table('warranty')
            ->whereNull('deleted_at')
            ->where('approved', 1)
            ->whereIn('user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')
                    ->where('id', $user_id)
                    ->orWhere('creator_id', $user_id);
            })
            ->count();*/
        /*$dh = DB::table('roll_transfer')
            ->where('approved', 1)
            ->whereNull('deleted_at')
            ->count();
        $zb = DB::table('precut')
            ->whereNull('deleted_at')
            ->where('status', 0)
            ->whereIn('user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')
                    ->where('id', $user_id)
                    ->orWhere('creator_id', $user_id);
            })
            ->count();*/
        $panel = [];
        $panel = [
            /*[
                'title' => ts('dealer'),
                'no' => $jxs,
                'icon' => 'fa-user',
                'url' => '/admin/dealer?status=1',
            ],
            [
                'title' => ts('AZSL'),
                'no' => $kh,
                'icon' => 'fa-wrench',
                'url' => '/admin/warranty?status=1',
            ],*/
            /*[
                'title' => ts('DANTC'),
                'no' => $zb,
                'icon' => 'fa-cogs',
                'url' => '/admin/precut_deal',
            ],*/
            [],
        ];

        $wt1 = Warranty::where('approved', '=', 3)
            ->whereIn('user_id', function ($query) use ($admin_id) {
                $query->select('id')->from('users')
                    ->where('id', $admin_id)
                    ->orWhere('creator_id', $admin_id);
            })
            ->count();
        $wt2 = Warranty::where('approved', 1)
            ->where(function ($query) use ($admin_id) {
                $query->where('distributor_id', $admin_id)
                    ->orWhere(function ($query) use ($admin_id) {
                        $query->where(function ($q1) use ($admin_id) {
                            $q1->whereNull('distributor_id')
                                ->orWhere('distributor_id', '0');
                        })
                            ->whereIn('user_id', function ($query) use ($admin_id) {
                                $query->select('id')->from('users')
                                    ->where('id', $admin_id)
                                    ->orWhere('creator_id', $admin_id);
                            });
                    });
            })
            ->count();
        /*$wt2 = Warranty::where('approved', 1)
            ->whereIn('user_id', function ($query) use ($admin_id) {
                $query->select('id')->from('users')
                    ->where('id', $admin_id)
                    ->orWhere('creator_id', $admin_id);
            })
            ->count();*/
        $dh1 = RollTransfer::where('approved', '=', 0)
            ->where('created_by', $admin_id)
            ->count();
        $th1 = RollReturn::where('status', '=', 0)
            ->where('user_id', $admin_id)
            ->count();

        $roll1 = RollRestlen::where('user_id', $admin_id)
            ->where('restlen', 0)
            ->count();
        $roll2 = RollRestlen::where('user_id', $admin_id)
            ->where('restlen', '>', 0)
            ->count();
        $jxs = DB::table('users')
            ->where('status', 1)
            ->where('check_status', 1)
            ->where('creator_id', $admin_id)
            ->whereNull('deleted_at')
            ->where('user_type', 3)
            ->count();

        $checkDealers = Admin::where('check_status', 0)->where('creator_id', session('admin.id'))->where('user_type', 3)->count();

        $panel2 = [
            ts('ZBDB') => [
                [
                    'title' => ts('BRXZZBS'),
                    'no' => $wt1,
                    'icon' => 'fa-upload',
                    // 'url' => '/admin/warranty?status=3&startdate='.$dtime,
                    'url' => '/admin/warranty?status=3',
                ],
                [
                    'title' => ts('BRTGZBS'),
                    'no' => $wt2,
                    'icon' => 'fa-wrench',
                    // 'url' => '/admin/warranty?status=1&startdate='.$dtime,
                    'url' => '/admin/warranty?status=1',
                ],
            ],
            ts('MODB') => [
                [
                    'title' => ts('DSHDH'),
                    'no' => $dh1,
                    'icon' => 'fa-cogs',
                    'url' => '/admin/rolls-transfer?status=0',
                ],
                [
                    'title' => ts('DSHTH'),
                    'no' => $th1,
                    'icon' => 'fa-cog',
                    'url' => '/admin/rolls-return?status=0',
                ],
            ],
            ts('CPDB') => [
                [
                    'title' => ts('YFPJH'),
                    'no' => $roll1,
                    'icon' => 'fa-tasks',
                    'url' => '/admin/rolls?status=2',
                ],
                [
                    'title' => ts('DFPJH'),
                    'no' => $roll2,
                    'icon' => 'fa-tasks',
                    'url' => '/admin/rolls?status=0',
                ],
            ],
            ts('SJTJ') => [
                [
                    'title' => ts('dealer'),
                    'no' => $jxs,
                    'icon' => 'fa-user',
                    'url' => '/admin/dealer?status=1',
                ],
                [
                    'title' => ts('DJXSSH'),
                    'no' => $checkDealers,
                    'icon' => 'fa-user',
                    'url' => '/admin/dealer?check_status=0',
                ],
            ],
        ];

        return [
            'panel' => $panel,
            'panel2' => $panel2,

        ];
    }
    protected function gly_index(Request $request)
    {

        $sd = DB::table('users')
            ->where('status', 1)
            ->whereNull('deleted_at')
            ->where('user_type', 2)
            ->count();

        $jxs = DB::table('users')
            ->where('status', 1)
            ->where('check_status', 1)
            ->whereNull('deleted_at')
            ->where('user_type', 3)
            ->count();
        /*$kh = DB::table('warranty')
            ->whereNull('deleted_at')
            ->where('approved', 1)
            ->count();
        $dh = DB::table('roll_transfer')
            ->whereNull('deleted_at')
            ->where('approved', 0)
            ->count();*/

        // $wdea = DB::select("select count(w.id), u.creator_id as user_id from warranty as w left join users as u on u.id=w.user_id WHERE u.user_type=3 group by u.creator_id");
        // $wdis = DB::select("select count(w.id), user_id from warranty as w left join users as u on u.id=w.user_id WHERE u.user_type!=3 group by u.id");
        // $wuser = DB::table('users')->where('user_type', '!=', 3)->get(['id', 'abbr']);
        /*$uab = [];
        foreach ($wuser as $k => $v) {
            $v->count = 0;
            $uab[$v->id] = $v;
        }*/

        $panel = [
            [
                'title' => ts('distributor'),
                'no' => $sd,
                'icon' => 'fa-user',
                'url' => '/admin/distributor?status=1',
            ],
            [
                'title' => ts('dealer'),
                'no' => $jxs,
                'icon' => 'fa-user',
                'url' => '/admin/dealer?status=1',
            ],
            /*[
                'title' => ts('AZSL'),
                'no' => $kh,
                'icon' => 'fa-wrench',
                'url' => '/admin/warranty?status=1',
            ],*/
            /*[
                'title' => ts('DCLDH'),
                'no' => $dh,
                'icon' => 'fa-cogs',
                'url' => '/admin/verify/transfer?status=0',
            ],*/
            /*[
                'title' => ts('DCLZB'),
                'no' => $zb,
                'icon' => 'fa-cogs',
                'url' => '/admin/verify/warranty?status=0',
            ],*/
        ];

        $dtime = date('Y-m-d');
        /*$wt1 = Warranty::where('created_at', '>=', $dtime)
            ->where('approved', '=', 3)
            ->count();
        $wt2 = Warranty::where('created_at', '>=', $dtime)
            ->where('approved', 1)
            ->count();

        $dh1 = RollTransfer::where('created_at', '>=', $dtime)
            ->where('approved', '=', 0)
            ->count();
        $dh2 = RollTransfer::where('created_at', '>=', $dtime)
            ->where('approved', 1)
            ->count();

        $th1 = RollReturn::where('created_at', '>=', $dtime)
            ->where('status', '=', 0)
            ->count();
        $th2 = RollReturn::where('created_at', '>=', $dtime)
            ->where('status', 1)
            ->count();*/

        $wt1 = Warranty::where('approved', '=', 3)
            ->count();
        $wt2 = Warranty::where('approved', 1)
            ->count();
        /*$dh1 = RollTransfer::where('approved', '=', 0)
            ->count();
        $th1 = RollReturn::where('status', '=', 0)
            ->count();*/
        $dh1 = DB::table('roll_transfer as rr')
            ->leftJoin('roll_master as rm', 'rm.id', 'rr.roll_id')
            ->where('rr.approved', '=', 0)
            ->whereNotNull('rm.id')
            ->whereNull('rr.deleted_at')
            ->count();
        $th1 = DB::table('roll_return as rr')
            ->leftJoin('roll_master as rm', 'rm.id', 'rr.roll_id')
            ->where('rr.status', '=', 0)
            ->whereNotNull('rm.id')
            ->whereNull('rr.deleted_at')
            ->count();
        $pp1 = MakeMaster::where('status', '=', 0)
            ->count();
        $cx1 = ModelMaster::where('status', '=', 0)
            ->count();

        $rm0 = RollMaster::where('status', 0)->count();
        $rm1 = RollMaster::where('status', 1)->count();

        $checkDealers = Admin::where('check_status', 0)->where('status', 1)->where('user_type', 3)->count();

        $requestDeleteNums = DB::table('warranty_delete')->whereNull('deleted_at')->count();

        $warranty = DB::table('warranty_notice')->whereNull('deleted_at')->get();
        $ids = '';
        if (empty($warranty) || $warranty->isEmpty()) {
            $warrantyNoticeNum  = 0;
        } else {
            $warrantyNoticeNum = count($warranty);
            foreach ($warranty as $item) {
                $ids .= $item->warranty_id . ',';
            }
            $ids = rtrim($ids, ',');
        }

        /*$rm1 = DB::table('roll_master as rm')
            ->leftJoin('roll_sales as rs', 'rm.id', '=', 'rs.roll_id')
            ->whereNull('rm.deleted_at')
            ->whereNull('rs.roll_id')
            ->whereNull('rs.deleted_at')
            ->count();*/

        $zb = [
            [
                'title' => ts('BRXZZBS'),
                'no' => $wt1,
                'icon' => 'fa-upload',
                // 'url' => '/admin/warranty?status=3&startdate='.$dtime,
                'url' => '/admin/warranty?status=3',
            ],
            [
                'title' => ts('BRTGZBS'),
                'no' => $wt2,
                'icon' => 'fa-wrench',
                // 'url' => '/admin/warranty?status=1&startdate='.$dtime,
                'url' => '/admin/warranty?status=1',
            ],
            [
                'title' => ts('SQSCZB'),
                'no' => $requestDeleteNums,
                'icon' => 'fa-user',
                'url' => '/admin/warranty_delete',
            ],
        ];

        if (cWPC()) {
            $zb[] = [
                'title' => ts('xzzb'),
                'icon' => 'fa-plus',
                'url' => '/admin/warranty/create',
            ];
        }
        $xzdmCount = DB::table('users')
            ->where('user_type', '=', 3)
            ->where('status', '=', 1)
            ->whereBetween('created_at', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])
            ->count();

        $scdmCount = DB::table('users')
            ->where('user_type', '=', 3)
            ->where('status', '!=', 1)
            ->whereBetween('updated_at', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])
            ->count();

        $userStoreLogs = (new StoreService())->getStoreChangeList();

        $panel2 = [

            ts('ZBDB') => $zb,
            ts('MODB') => [
                [
                    'title' => ts('RMST0'),
                    'no' => $rm0,
                    'icon' => 'fa-tasks',
                    'url' => '/admin/rolls?status=0',
                ],
                [
                    'title' => ts('RMST1'),
                    'no' => $rm1,
                    'icon' => 'fa-tasks',
                    'url' => '/admin/rolls?status=1',
                ],
                [
                    'title' => ts('DSHDH'),
                    'no' => $dh1,
                    'icon' => 'fa-cogs',
                    'url' => '/admin/verify/transfer?status=0',
                ],
                [
                    'title' => ts('DSHTH'),
                    'no' => $th1,
                    'icon' => 'fa-cog',
                    'url' => '/admin/verify/rolls_return?status=0',
                ],
            ],
            ts('CXDB') => [
                [
                    'title' => ts('DQRPP'),
                    'no' => $pp1,
                    'icon' => 'fa-tag',
                    'url' => '/admin/setting/make?status=0',
                ],
                [
                    'title' => ts('DQRCX'),
                    'no' => $cx1,
                    'icon' => 'fa-car',
                    'url' => '/admin/setting/model?status=0',
                ],
            ],
            ts('SJTJ') => [
                [
                    'title' => ts('distributor'),
                    'no' => $sd,
                    'icon' => 'fa-user',
                    'url' => '/admin/distributor?status=1',
                ],
                [
                    'title' => ts('dealer'),
                    'no' => $jxs,
                    'icon' => 'fa-user',
                    'url' => '/admin/dealer?status=1',
                ],
                [
                    'title' => ts('DJXSSH'),
                    'no' => $checkDealers,
                    'icon' => 'fa-user',
                    'url' => '/admin/dealer?check_status=0',
                ],
                [
                    'title' => "门店新增",
                    'no' => $userStoreLogs[UserStoreLogs::TYPE_NEW] ?? 0,
                    'icon' => 'fa-user-plus',
                    'url' => '/admin/dealer?check_status=1&type='.UserStoreLogs::TYPE_NEW,
                ],
                [
                    'title' => "门店升级",
                    'no' => $userStoreLogs[UserStoreLogs::TYPE_UP] ?? 0,
                    'icon' => 'fa-arrow-up',
                    'url' => '/admin/dealer?check_status=1&type='.UserStoreLogs::TYPE_UP,
                ],
                [
                    'title' => "门店降级",
                    'no' => $userStoreLogs[UserStoreLogs::TYPE_DOWN] ?? 0,
                    'icon' => 'fa-arrow-down',
                    'url' => '/admin/dealer?check_status=1&type='.UserStoreLogs::TYPE_DOWN,
                ],
                [
                    'title' => "门店停用",
                    'no' => $userStoreLogs[UserStoreLogs::TYPE_STOP] ?? 0,
                    'icon' => 'fa-trash',
                    'url' => '/admin/dealer?type='.UserStoreLogs::TYPE_STOP,
                ],
            ],
            ts('ZBBJ')  => [
                [
                    'title' => ts('JBSN'),
                    'no'    => $warrantyNoticeNum,
                    'icon'  => 'fa-user',
                    'url'   => '/admin/warranty?notice_type=1',
                ]
            ],
            ts('DMTJ')  => [
                // ts('ZBBJ')  => [
                [
                    'title' => ts('XZDM'),
                    'no'    => $xzdmCount,
                    'icon'  => 'fa-user',
                    'url'   => '/admin/dealer',
                ],
                [
                    'title' => ts('SCDM'),
                    'no'    => $scdmCount,
                    'icon'  => 'fa-user',
                    'url'   => '/admin/dealer-o',
                ]
            ]
        ];
        return [
            // 'panel' => $panel,
            'panel2' => $panel2,

        ];
    }

    public function index(Request $request)
    {
        $page = [
            'page_name' => 'DASHBOARD',
            'title' => ts('DASHBOARD')
        ];
        $user_id = session()->get('admin.id');
        $user_type = session()->get('admin.user_type');
        $role_id = session()->get('admin.role_id');
        $chart = [];
        if ($user_type == 1 && !empty($role_id)) {
            $data = $this->gly_index($request);

            return view('admin.index.index-gly', [
                'data' => $data,
                'page' => $page,
                'charts' => $chart,
            ]);
        } elseif ($user_type == 2) {
            $data = $this->sd_index($request);
            return view('admin.index.index-sd', [
                'data' => $data,
                'page' => $page,
                'charts' => $chart,
            ]);
        } else if ($user_type > 3 && !empty($role_id)) {
            // abort(404);
            $role = Roles::find($user_type);
            $permission = [];
            $permission = $role->permissions()->first();

            if (empty($role->id) || empty($permission->id)) {
                session()->forget('admin');
                return redirect('admin/login');
            }
            return redirect('/admin/' . $permission->url);
        } else {
            return abort(404);
        }


        return view('admin.index.index', [
            'data' => $data,
            'page' => $page,
            'charts' => $chart,
        ]);
    }
}
